import BleManager from '@UTILS/BleManager'
import BleCharacteristicsConstants from '@CONSTANTS/BleCharacteristicsConstants'
import LastTreatmentParser from '@UTILS/LastTreatmentParser'
import ReportDataParser from '@UTILS/ReportDataParser'

type ReadDeviceStatusListener = (data:any) => void

export default class BleDeviceFunctionality {
  private timer: number = 1

  private readDeviceStatusListener: ReadDeviceStatusListener = () => {}

  addReadDeviceStatusListener = (readDeviceStatusListener: ReadDeviceStatusListener) => {
    this.readDeviceStatusListener = readDeviceStatusListener
  }

  removeReadDeviceStatusListener = () => {
    this.stopStatusPolling()
    this.readDeviceStatusListener = () => {}
  }

  startStatusPolling = () => {
    this.readDeviceStatus().then((res) => {
      this.readDeviceStatusListener(res)
    })
    this.timer = setInterval(() => {
      this.readDeviceStatus().then((res) => {
        this.readDeviceStatusListener(res)
      })
    }, 1000)
  }

  stopStatusPolling=() => {
    clearInterval(this.timer)
  }

  setIntensity = (intensity: number) => {
    this.stopStatusPolling()
    console.log('BleDeviceFunctionality: setIntensity')
    return BleManager.writeCommand(`amplitude ${intensity}\n`).finally(() => {
      this.startStatusPolling()
    })
  }

  startTreatment = (intensity: number) => {
    console.log('BleDeviceFunctionality: startTreatment')
    return BleManager.writeCommand(`start 0 ${intensity}\n`).finally(() => {
      this.startStatusPolling()
    })
  }

  pauseTreatment = () => {
    this.stopStatusPolling()
    console.log('BleDeviceFunctionality: pause treatment')
    return BleManager.writeCommand('pause\n').finally(() => {
      this.startStatusPolling()
    })
  }

  resumeTreatment = () => {
    this.stopStatusPolling()
    console.log('BleDeviceFunctionality: resumeTreatment')
    return BleManager.writeCommand('resume\n').finally(() => {
      this.startStatusPolling()
    })
  }

  stopTreatment = () => {
    this.stopStatusPolling()
    console.log('BleDeviceFunctionality: stopTreatment')
    return BleManager.writeCommand('stop\n').finally(() => {
      this.startStatusPolling()
    })
  }

  getLastTreatmentData = async () => {
    console.log('BleDeviceFunctionality: get last treatment data')
    const data = await BleManager.readCommand(BleCharacteristicsConstants.LAST_TREATMENT_CHARACTERISTIC_UUID)
    return LastTreatmentParser.parse(data)
  }

  getReportData = async () => {
    console.log('BleDeviceFunctionality: get report data')
    const data = await BleManager.readCommand(BleCharacteristicsConstants.REPORT_CHARACTERISTIC_UUID)
    return ReportDataParser.parse(data)
  }

  // 治疗过程中读取状态
  readDeviceStatus = async () => {
    return BleManager.readDeviceStatus()
  }

  clearPassword = () => {
    console.log('BleDeviceFunctionality: clearPassword')
    return BleManager.writeCommand('clearpwd\n')
  }
}
